#!/bin/sh

action=$1
CSI="\033["
FG="${CSI}38;5;"
BG="${CSI}48;5;"

ENDC="${CSI}0m"

base_repo='git@gitlab.3ren.cn:shadow-moon/utils.git'
list_file='.npmrc'

function clear_node_modules() {
    rm -rf ./node_modules
    printf "${FG}12mDir 'node_modules' removed${ENDC}\n"
}

function showUsage() {
    printf "${FG}3mUsage: install.sh [action]\n"
    cat << 'EOF'
    action:
    `clear` | `clr` | `c`: Remove dir node_modules
    `install` | `i`: Calls npm install
    `clear-install` | `ii` | `ci`: `clear` then `install`
EOF
}

function sync_base_files() {
    printf "${FG}6mSync base files from '${base_repo}'...${ENDC}\n"
    tmpd=$(mktemp -d)
    pushd $tmpd
    git clone $base_repo base
    popd

    while read line
    do
            src_file="${tmpd}/${line}"
            target_file="$line"

            if [[ -z $src_file ]]; then
                continue

            fi

            if [[ ! -f $src_file ]]; then
                printf "${FG}9mSource file ${ENDC}'${src_file}'${ENDC} ${FG}9mnot exist while listed in ${ENDC}'files.lst'\n"
                exit 1
            fi

            if [[ -e $target_file ]]; then
                printf "${FG}9m${target_file}${ENDC} exists!\n" 
                exit 2
            fi

            echo cp -v $src_file $target_file
    done < "${tmpd}/base/${list_file}"

    rm -rf $tmpd
}

case $action in
    'clear' | 'clr') clear_node_modules ;;
    'clear-install' | 'clin' | 'ii' ) clear_node_modules && npm install ;;
    'install' | 'i' ) npm install ;;
    * ) showUsage; exit 2;;
esac

sync_base_files
